import 'dart:io';
import 'package:wechat_assets_picker/wechat_assets_picker.dart';
import 'file_ext.dart';
import '../utils/common.dart';

/// List 扩展
extension ListExt on List? {
  /// 遍历
  forEachIndexed<T>(Function(int index, T item) action) {
    if (this == null) {
      return;
    }
    var index = 0;
    for (T item in this!) action(index++, item);
  }

  ///列表字段拼接
  String appendStr<T>(
    String Function(T item) action, {
    String divStr = ",",
  }) {
    if (isEmptyOrNull(this)) {
      return "";
    }
    var sb = StringBuffer();
    this!.forEachIndexed<T>((index, item) {
      var itemStr = action.call(item);
      sb.write(itemStr);
      if (index != this!.length - 1) {
        sb.write(divStr);
      }
    });
    return sb.toString();
  }

  /// 遍历
  Iterable<T>? mapIndexed<T, E>(T Function(int index, E item) action) {
    if (this == null) {
      return null;
    }
    var index = 0;

    return this!.map<T>((e) => action.call(index++, e));
  }

  Future<List<File>> getFiles(
      {bool isLoading = true, bool isCompress = true}) async {
    if (this == null) {
      if (isLoading) hideLoading();
      return [];
    }
    if (this is List<AssetEntity>) {
      if (isLoading) showLoading();
      List<File> files = [];
      try {
        for (int i = 0; i < this!.length; i++) {
          File? file = await this![i].file;
          if (isCompress) {
            file = await file?.compressFile();
          }
          if (file != null) {
            files.add(file);
          }
        }
      } catch (e) {
        showToastWarning("压缩图片失败：$e");
      }
      if (isLoading) hideLoading();
      return files;
    }
    if (isLoading) hideLoading();
    return [];
  }
}
